package com.yy.controller.common;

import com.yy.common.config.RCConfig;
import com.yy.common.constant.Constants;
import com.yy.common.utils.StringUtils;
import com.yy.common.utils.file.FileUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * 通用静态资源下载Controller
 *
 * @author SantaAntilles
 * @timeSnapsot 2023-12-26 19:51
 * 我就认为所有/profile开头的都是请求后台资源，你后期要是加权限验证的话这些记得放行
 */

@RestController
@RequestMapping("/common")
public class StaticResourceAccessController {

    private static final Logger log = LoggerFactory.getLogger(StaticResourceAccessController.class);

    @PostMapping("/download")
    public void accessResourceGet(HttpServletResponse response, HttpServletRequest request,
                                  @RequestParam("filename") String resource) throws IOException {
        try {
            if (!FileUtils.checkAllowDownload(resource)) {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = RCConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }
}